import 'package:flutter_mwm/util/util.dart';
import 'package:permission_handler/permission_handler.dart';

abstract class StrImpl {
  static const String KEY_ACCOUNT = 'account';
  static final String KEY_PASSWORD = 'password';
}

abstract class HttpCallbackImpl {
  void onResult(int what, Object tag, String result);

  void onError(int what, Object tag, String e);
}

abstract class PermissionImpl {
  void onPermission(Permission permission, bool success);
}

abstract class ServerImpl {
  static final String KEY_BASEURL = 'baseUrl';
  static final String KEY_IPADD = 'serverIpAdd';
  static final String KEY_PORT = 'serverPort';
  static final String KEY_HTTPORHTTPS = 'httpOrHttps';
  static final String DEFAULT_HTTPORHTTPS = 'http';
  static final String DEFAULT_IPADD = '192.168.20.96';
  static final String DEFAULT_PORT = '8080';
  static final String NAMESPACE = 'mwm';
  static final String ACTION = 'action.do?method=';

/*默认端口9080*/
  static String getIpAddressByDefaultPort(String ipAdd, String defaultPort) {
    if (!portValid(defaultPort)) {
      throw FormatException("端口号范围0～65535，当前端口号：" + defaultPort);
    } else
      return getIpAddress(ipAdd, "192.168.0.1", defaultPort);
  }

  /*
   * @param ipAdd 默认端口9080
   *              1、（ip地址中包含端口号）192.168.0.1:9081
   *              2、（ip地址中不含端口号，需要加上默认端口9080）192.168.0.1
   * @return 1、192.168.0.1:9081
   * 2、192.168.0.1:9080
  */
  static String getIpAddress(
      String ipAdd, String defaultIp, String defaultPort) {
    try {
      if (!portValid(defaultPort)) {
        throw FormatException("端口号范围0～65535，当前端口号：" + defaultPort);
      }
      String address;
      if (TextUtils.isEmpty(ipAdd)) {
        address = TextUtils.isEmpty(defaultPort)
            ? defaultIp
            : ("$defaultIp:$defaultPort");
        return address;
      }
      if (ipAdd.contains(":")) {
        //包含端口
        address = ipAdd;
      } else {
        //不包含端口
        address =
            TextUtils.isEmpty(defaultPort) ? ipAdd : "$ipAdd:$defaultPort";
      }
      return address;
    } catch (e) {
      e.printStackTrace();
      return ipAdd;
    }
  }

  /*
   * @param http      http或者https
   * @param ipAdd     IP地址
   * @param port      端口号
   * @param nameSpace test
   * @return http://192.168.0.155:9080/test/ 必须以"/"结尾
   */
  static String getBaseUrl(
      String http, String ipAdd, String port, String nameSpace) {
    if (!portValid(port)) {
      throw FormatException("端口号范围0～65535，当前端口号：" + port);
    } else {
      String url = getIpAddressByDefaultPort(ipAdd, port);
      if (TextUtils.isEmpty(nameSpace)) {
        return "$http://$url/$nameSpace";
      } else
        return "$http://$url/$nameSpace/";
    }
  }

  static bool portValid(String port) {
    try {
      if (TextUtils.isEmpty(port)) return true;
      int portInt = int.parse(port);
      return (portInt >= 0 && portInt <= 65535);
    } catch (e) {
      return false;
    }
  }
}
